// Ionic_SDK
//
// 保佑没Bug
//
// Created by AS on 2019/1/2.
//
// Copyright © 2018 AS. All rights reserved.
//

#import "AFNetworking.h"
#import "SCXLoadingView.h"
#import <ZipArchive/ZipArchive.h>
#import "TYDownloadUtility.h"
@interface SCXLoadingView()<ZipArchiveDelegate>
/**  */
@property (nonatomic,strong) UILabel *versionLabel;
/**  */
@property (nonatomic,strong) UILabel *statusLabel;
/**  */
@property (nonatomic,strong) UIProgressView *progressView;
/**  */
@property (nonatomic,copy) NSString *serverVersion;
/**  */
@property (nonatomic,strong) UIButton *repeatButton;

/**  */
@property (nonatomic,strong) UIActivityIndicatorView *indicatorView;

@end
@implementation SCXLoadingView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubView];
        [self getPackageInfo];
        
        
    }
    return self;
}


-(void)initSubView{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webViewLoadingProgress:) name:@"WKWebViewLoadingProgressNotficiation" object:nil];
    
    self.backgroundColor = [UIColor whiteColor];
    CGFloat height = self.frame.size.height;
    CGFloat width = self.frame.size.width;
    
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    
    backgroundImageView.image = [UIImage imageNamed:@"launch"];
    
    [self addSubview:backgroundImageView];
    
    
    self.versionLabel = [[UILabel alloc]initWithFrame: CGRectMake(0, self.height - 30, self.frame.size.width, 15)];
    self.versionLabel.font = [UIFont systemFontOfSize:12];
    self.versionLabel.textColor = [UIColor whiteColor];
    self.versionLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview: self.versionLabel];
    
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(40,self.versionLabel.y - 20, width - 80, 4)];
    self.progressView.progress = 0.5;
    self.progressView.hidden = YES;
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 3.0f);
    self.progressView.layer.cornerRadius = 3;
    [self addSubview:self.progressView];
    
    
    self.statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(40,self.progressView.y - 20, self.progressView.frame.size.width, 15)];
    self.statusLabel.font = [UIFont systemFontOfSize:14];
    self.statusLabel.textColor = [UIColor whiteColor];
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.text = @"检查更新中...";
    [self addSubview:self.statusLabel];
    
    
    
    
    self.indicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake((width - 50 ) / 2, self.progressView.frame.origin.y - 60, 50, 50)];
    self.indicatorView.hidesWhenStopped = YES;
    self.indicatorView.hidden = YES;
    self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [self addSubview:self.indicatorView];
    
    self.repeatButton = [UIButton new];
    self.repeatButton.backgroundColor = [UIColor colorWithRed:68/255.0 green:145/255.0 blue:205/255.0 alpha:1.0];
    self.repeatButton.layer.masksToBounds = YES;
    self.repeatButton.layer.cornerRadius = 5;
    self.repeatButton.frame = CGRectMake((width-200)/2,(height - 100)/2, 200, 40);
    [self.repeatButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.repeatButton setTitle:@"点击重试" forState:UIControlStateNormal];
    [self.repeatButton addTarget:self action:@selector(repeatAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.repeatButton];
    self.repeatButton.hidden = YES;
    
}

-(void)setStatus:(NSString *)status{
    self.statusLabel.text = status;
}

-(void)repeatAction{
    
    [self getPackageInfo];
}

-(void)webViewLoadingProgress:(NSNotification *)notification{
    NSDictionary *dict = notification.userInfo;
    double progress = [dict[@"progress"] doubleValue];
    if (progress == 1) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        [UIView animateWithDuration:0.4 animations:^{
            self.alpha = 0.00001;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
}

-(void)getPackageInfo{
    self.statusLabel.text = @"检查更新中...";
//    NSString *url = @"http://192.168.103.169/ionic/lottery/zjjh/ios/info.json";
//    NSString *url = @"http://192.168.103.41/zjjh/ios/info.json";
    NSString *url = @"http://47.244.180.213:8200/api/package/getPackage?stageType=mk&packageName=iOS";
    self.statusLabel.hidden = NO;
    self.repeatButton.hidden = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *iOS = responseObject[@"data"];
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *appVersion = iOS[@"appVersion"];
        NSArray *hostVersions = [app_Version componentsSeparatedByString:@"."];
        NSArray *versions = [appVersion componentsSeparatedByString:@"."];
        NSString *packageUrl = iOS[@"appUrl"];
        if([hostVersions[0] intValue] < [versions[0] intValue] ){
            [self alert:packageUrl];
        }else if ([hostVersions[0] intValue] <= [versions[0] intValue] && [hostVersions[1] intValue] < [versions[1] intValue]){
            [self alert:packageUrl];
        }else if ([hostVersions[0] intValue] <= [versions[0] intValue] && [hostVersions[1] intValue] <= [versions[1] intValue] && [hostVersions[2] intValue] < [versions[2] intValue]){
            [self alert:packageUrl];
        }else{
            NSString *serveVersion = iOS[@"version"];
            self.serverVersion = serveVersion;
            NSString *locationVersion = [defaults stringForKey:@"appVersion"];
            NSString *url = iOS[@"url"];
            self.versionLabel.text = [NSString stringWithFormat:@"版本：%@",serveVersion];
            if (!locationVersion || ![serveVersion isEqualToString:locationVersion]) {
                [self downloadPackage:url];
            }else{
                [self completion];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        self.statusLabel.hidden = YES;
        self.progressView.hidden = YES;
        self.repeatButton.hidden = NO;
    }];
}


-(void)alert:(NSString *)url{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"中金计划" message:@"发现新版本" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        exit(0);
    }];
    UIAlertAction *update = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        exit(0);
    }];
    
    [alert addAction:cancel];
    [alert addAction:update];
    [self.viewController presentViewController:alert animated:YES completion:nil];
}

-(void)downloadPackage:(NSString *)url{
    self.progressView.progress = 0;
    self.statusLabel.text = @"资源下载中...";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    self.progressView.hidden = NO;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progressView.progress = downloadProgress.fractionCompleted;
            
            int64_t totalCount = downloadProgress.totalUnitCount;
            int64_t currentCount = downloadProgress.completedUnitCount;
            NSString *total = [NSString stringWithFormat:@"%.1f",[TYDownloadUtility calculateFileSizeInUnit:totalCount]];
            NSString *current = [NSString stringWithFormat:@"%.1f",[TYDownloadUtility calculateFileSizeInUnit:currentCount]];
            self.statusLabel.text = [NSString stringWithFormat:@"资源下载中... %@%@ / %@%@",current,[TYDownloadUtility calculateUnit:currentCount],total,[TYDownloadUtility calculateUnit:totalCount]];
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:[[self createPath] stringByAppendingPathComponent:response.suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (!error) {
            [self freedFile:[filePath path]];
        }else{
            self.statusLabel.hidden = YES;
            self.progressView.hidden = YES;
            self.repeatButton.hidden = NO;
            NSLog(@"%@",error);
        }
    }];
    [task resume];
}

-(NSString *)createPath{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [document stringByAppendingPathComponent:@"ionic"];
    if (![fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        if([fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]){
            return path;
        }else{
            return nil;
        }
    }else{
        return path;
    }
}
/** 解压文件 */
-(void)freedFile:(NSString *)filePath{
    self.statusLabel.text = @"解压文件...";

    NSFileManager *fileManager = [NSFileManager defaultManager];
    ZipArchive *zip = [[ZipArchive alloc]initWithFileManager:fileManager];

    if([zip UnzipOpenFile:filePath]){
        NSLog(@"==");
        if([zip UnzipFileTo:[self createPath] overWrite:YES]){
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager removeItemAtPath:filePath error:nil];
            [self completion];
        }else{
            NSLog(@"----");
        }
    }else{
        NSLog(@"--");
    }
    [zip UnzipCloseFile];
    
}

-(void)ErrorMessage:(NSString *)msg{
    NSLog(@"%@",msg);
}

-(BOOL)OverWriteOperation:(NSString *)file{
    NSLog(@"%@",file);
    return YES;
}


/** 全部准备完成 */
-(void)completion{
    if (self.completionBlock) {
        self.completionBlock();
    }
    self.progressView.hidden = YES;
    self.indicatorView.hidden = NO;
    [self.indicatorView startAnimating];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.serverVersion forKey:@"appVersion"];
    self.statusLabel.text = @"正在加载中...";
}

@end




